package com.drcoffee.drcoffeemall.service.impl;

import com.drcoffee.drcoffeemall.entry.*;
import com.drcoffee.drcoffeemall.mapper.PartsMapper;
import com.drcoffee.drcoffeemall.mapper.ShoppingCartMapper;
import com.drcoffee.drcoffeemall.mapper.UserMapper;
import com.drcoffee.drcoffeemall.service.ShoppingCartService;
import com.drcoffee.drcoffeemall.util.DiscountedPriceUtil;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.util.*;

@Slf4j
@Service
@Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
public class ShoppingCartServiceImpl implements ShoppingCartService {

    @Autowired
    ShoppingCartMapper shoppingCartMapper;

    @Autowired
    UserMapper userMapper;

    @Autowired
    PartsMapper partsMapper;


    @Autowired
    RedisTemplate<String, Object> redisTemplate;

    private String token;

    @PostConstruct
    public void init() {
        getToken();
    }

    @Override
    @Scheduled(fixedRate = 24 * 60 * 60 * 1000)
    public void getToken(){
        try {
            String url = "https://weapp.lexy.cn/lexyapi/getToken?ent_id=qy202307311690791200&ent_secret=66cc4211eaa37f79f3608353e4e28c36";
            HttpClient client = HttpClientBuilder.create().build();
            HttpGet request = new HttpGet(url);
            HttpResponse response = client.execute(request);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == HttpStatus.OK.value()) {
                InputStream inputStream = response.getEntity().getContent();
                Gson gson = new Gson();
                JsonObject jsonObject = gson.fromJson(new InputStreamReader(inputStream), JsonObject.class);
                token = jsonObject.get("token").getAsString();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("获取到的token值："+this.token);
    }

    @Override
    public ResponseEntity<Object> getErpStock(String array){
//        this.getToken();
        try {
            String url = "https://weapp.lexy.cn/lexyapi/kbs/product1/KBS_shop_repertory";
            HttpClient client = HttpClientBuilder.create().build();
            HttpPost request = new HttpPost(url);
            // 添加请求头（如果需要）
            request.addHeader("token", token);
            request.setEntity(new StringEntity(array, ContentType.APPLICATION_JSON));

            HttpResponse response = client.execute(request);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == HttpStatus.OK.value()) {

                InputStream inputStream = response.getEntity().getContent();
                Gson gson = new Gson();
                JsonObject jsonObject = gson.fromJson(new InputStreamReader(inputStream), JsonObject.class);
                System.out.println("123456"+jsonObject);
//                JsonArray listArray = (JsonArray) jsonObject.get("data");
//                JsonArray listArray = jsonObject.getAsJsonArray(list);
                String list = String.valueOf(jsonObject.get("data"));
                System.out.println("获取到的值是55555"+list);
//                ArrayList<String> imgValues = new ArrayList<>();
                HashMap<String,List<String>> map = new HashMap<>();
                if (list !=null){
                    JSONParser parser = new JSONParser();
                    JSONObject jsonObject1 = (JSONObject) parser.parse(list);
                    JSONArray list1 = (JSONArray) jsonObject1.get("list");
                    for (Object obj : list1) {
                        JSONObject item = (JSONObject) obj;
                        String IMG01 = (String) item.get("IMG01");
                        if (map.containsKey("IMG01")) {
                            map.get("IMG01").add(IMG01);
                        } else {
                            List<String> values = new ArrayList<>();
                            values.add(IMG01);
                            map.put("IMG01", values);
                        }
                    }
                    System.out.println("转换后的map："+map);
                }

                // 遍历数组中的每个对象
//                Iterator<JSONObject> iterator = list1.iterator();
//                while (iterator.hasNext()) {
//                    JSONObject obj = iterator.next();
//                    String img01 = (String) obj.get("IMG01");
//                    Long img10 = (Long) obj.get("IMG10");
//                    imgValues.add("IMG01: " + img01 + ", IMG10: " + img10);
//                }

//                System.out.println("转换后的数组："+ imgValues);


//                String list = String.valueOf(jsonObject.get("data"));
//                System.out.println("获取到的料号值"+list);

                return ResponseEntity.ok(map);
            } else {
                return ResponseEntity.status(statusCode).body("请求失败，状态码错误: " + statusCode);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("错误: " + e.getMessage());
        }
    }




    @Override
    public Result getCart(String Token, String search, String language) {
        try {
            User user = (User) redisTemplate.opsForValue().get(Token);
            if (user != null) {
                String price_type = getPriceType("c", user);
                List<Attachment> attachmentList = shoppingCartMapper.getCart(user.getAccount(), '%' + search + '%', price_type, language);
                // BigDecimal total = new BigDecimal(0);

                /*
                 * 价格处理
                 * */

                // 特价条件：国内企业用户 && 没有折扣
                List<SpecialPrice> specialPrice = null;
                if (user.getPermission_id() == 1 && (user.getDiscount_one().compareTo(BigDecimal.ZERO) == 0 || user.getDiscount_two().compareTo(BigDecimal.ZERO) == 0)) {
                    specialPrice = partsMapper.getSpecialPrice(user.getErp_code());
                }

                for (Attachment attachment : attachmentList) {
                    // 折后价格
                    // BigDecimal discountRate = userMapper.getDiscountById(user.getAccount());
                    // BigDecimal bigDecimal = calculateDiscountedPrice(attachment.getPrice(), discountRate);
                    BigDecimal bigDecimal = DiscountedPriceUtil.getDiscountedPrice(attachment.getPrice(), user);
                    attachment.setDiscounted_price(bigDecimal);

                    if (specialPrice != null) {
                        for (SpecialPrice special : specialPrice) {
                            if (Objects.equals(special.getPart_code(), attachment.getPart_code())) {
                                attachment.setDiscounted_price(special.getPrice());
                            }
                        }
                    }
                    // 价格小计
                    BigDecimal price = attachment.getDiscounted_price().multiply(BigDecimal.valueOf(attachment.getQuantity()));
                    attachment.setSubtotal(price);
//                    total = total.add(price);
                }
                return new Result(1, "SUCCESS", "", attachmentList);
            } else {
                return new Result(-1, "ERROR", "user is null", null);
            }
        } catch (Exception e) {
            log.error("===================== getCart()异常： =====================", e);
            return new Result(-1, "ERROR", e.getMessage(), null);
        }
    }

    @Override
    public Result addToCart(String Token, Attachment attachment) {
        User user = (User) redisTemplate.opsForValue().get(Token);
        try {
            if (user != null) {
                List<Cart> cartList = shoppingCartMapper.getCartByattachment_id(user.getAccount(), attachment.getPart_code());
                if (!cartList.isEmpty()) {
                    Integer quantity = attachment.getQuantity() + cartList.get(0).getQuantity();

                    attachment.setQuantity(quantity);
                    updateQuantityById(user.getAccount(), attachment);
                    return new Result(1, "SUCCESS", "Successfully added to cart", null);
                } else {
                    Cart cart = new Cart();
                    cart.setPart_code(attachment.getPart_code());
                    cart.setQuantity(attachment.getQuantity());
                    cart.setUser_account(user.getAccount());
                    shoppingCartMapper.addToCart(cart);
                }
                return new Result(1, "SUCCESS", "Successfully added to cart", null);
            } else {
                return new Result(-1, "ERROR", "User is Null", null);
            }
        } catch (Exception e) {
            log.error("===================== addToCart()异常： =====================", e);
            return new Result(-1, "ERROR", e.getMessage(), null);
        }
    }

    @Override
    public Result removeFromCart(String Token, List<String> part_code) {
        try {
            User user = (User) redisTemplate.opsForValue().get(Token);
            if (user != null) {
                shoppingCartMapper.deletePartByCode(user.getAccount(), part_code);
                return new Result(1, "SUCCESS", "Successfully deleted", null);
            } else {
                return new Result(-1, "ERROR", "user is null", null);
            }
        } catch (Exception e) {
            log.error("===================== deletePartByCode()异常： =====================", e);
            return new Result(-1, "ERROR", e.getMessage(), null);
        }
    }

    @Override
    public Result updateQuantityById(String account, Attachment attachment) {
        try {
            Cart cart = new Cart();
            if (attachment.getQuantity() < 1) {
                return new Result(2, "WARN", "", null);
            }
            cart.setQuantity(attachment.getQuantity());
            cart.setUser_account(account);
            cart.setPart_code(attachment.getPart_code());
            shoppingCartMapper.updateQuantityById(cart);
            return new Result(1, "SUCCESS", "", null);
        } catch (Exception e) {
            log.error("===================== updateQuantityById()异常： =====================", e);
            return new Result(-1, "ERROR", e.getMessage(), null);
        }
    }

    /*
     * 根据料号、数量、用户类型、折扣 计算总价格
     * */
    @Override
    public ResponseEntity<Object> getTotal(String Token, List<String> part_codes) {
        Map<String, Object> resultMap = new HashMap<>();
        User user = (User) redisTemplate.opsForValue().get(Token);
        List<ProductQuantity> checkPartList = shoppingCartMapper.getCartByAccountAndPartCodes(user.getAccount(), part_codes);

        String price_type = getPriceType("b", user);

        // 特价条件：国内企业用户 && 没有折扣
        List<SpecialPrice> specialPrice = null;
        if (user.getPermission_id() == 1 && (user.getDiscount_one().compareTo(BigDecimal.ZERO) == 0 || user.getDiscount_two().compareTo(BigDecimal.ZERO) == 0)) {
            specialPrice = partsMapper.getSpecialPrice(user.getErp_code());
        }

        /* 价格处理 */
        // 折前合计价格
        BigDecimal beforeTotal = new BigDecimal(0);
        // 折后合计价格
        BigDecimal total = new BigDecimal(0);
        for (ProductQuantity checkPart : checkPartList) {
            String language;
            if (user.getPermission_id() == 2) {
                language = "EN";
            } else {
                language = "CN";
            }

            Attachment attachment = partsMapper.getAttachmentByPartCode(checkPart.getPart_code(), price_type, language);
            if (attachment != null){
                // 折前小计
                BigDecimal beforePrice = attachment.getPrice().multiply(BigDecimal.valueOf(checkPart.getQuantity()));
                beforeTotal = beforeTotal.add(beforePrice);
                // 折后价格
                BigDecimal bigDecimal = DiscountedPriceUtil.getDiscountedPrice(attachment.getPrice(), user);
                // 判断该用户是否存在商品特殊价格
                if (specialPrice != null) {
                    for (SpecialPrice special : specialPrice) {
                        if (Objects.equals(special.getPart_code(), checkPart.getPart_code())) {
                            bigDecimal = special.getPrice();
                        }
                    }
                }
                // 小计 (* 数量)
                BigDecimal price = bigDecimal.multiply(BigDecimal.valueOf(checkPart.getQuantity()));
                total = total.add(price);
            }
        }
        BigDecimal decrease = beforeTotal.subtract(total);
        // 合计价格
        resultMap.put("total", total);
        // 优惠 -￥
        resultMap.put("decrease", decrease);
        return new ResponseEntity<>(resultMap, HttpStatus.OK);
    }


    @Override
    public Result getCartsCount(String Token) {
        try {
            User user = (User) redisTemplate.opsForValue().get(Token);
            Integer carts_count = shoppingCartMapper.getCartsCount(user.getAccount());
            return new Result(1, "SUCCESS", "", carts_count);
        } catch (Exception e) {
            log.error("===================== getCartsCount()异常： =====================", e);
            return new Result(-1, "ERROR", e.getMessage(), null);
        }
    }

    @Override
    public ResponseEntity<Object> getCartProduct(String Token, String search, String language) {
        User user = (User) redisTemplate.opsForValue().get(Token);
        String price_type = getPriceType("c", user);
        List<Attachment> attachmentList = shoppingCartMapper.getCart(user.getAccount(), '%' + search + '%', price_type, language);
        // 特价条件：国内企业用户 && 没有折扣
        List<SpecialPrice> specialPrice = null;
        if (user.getPermission_id() == 1 && (user.getDiscount_one().compareTo(BigDecimal.ZERO) == 0 || user.getDiscount_two().compareTo(BigDecimal.ZERO) == 0)) {
            specialPrice = partsMapper.getSpecialPrice(user.getErp_code());
        }

        /* 价格处理 */
        // 折前合计价格
        BigDecimal beforeTotal = new BigDecimal(0);
        // 折后合计价格
        BigDecimal total = new BigDecimal(0);
        for (Attachment attachment : attachmentList) {
            // 折前小计
            BigDecimal beforePrice = attachment.getPrice().multiply(BigDecimal.valueOf(attachment.getQuantity()));
            beforeTotal = beforeTotal.add(beforePrice);
            // 折后价格
            BigDecimal bigDecimal = DiscountedPriceUtil.getDiscountedPrice(attachment.getPrice(), user);
            // 判断该用户是否存在商品特殊价格
            if (specialPrice != null) {
                for (SpecialPrice special : specialPrice) {
                    if (Objects.equals(special.getPart_code(), attachment.getPart_code())) {
                        bigDecimal = special.getPrice();
                    }
                }
            }
            // 小计 (* 数量)
            BigDecimal price = bigDecimal.multiply(BigDecimal.valueOf(attachment.getQuantity()));
            total = total.add(price);
        }
        BigDecimal decrease = beforeTotal.subtract(total);
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("productList", attachmentList);
        // 合计价格
        resultMap.put("total", total);
        // 优惠 -￥
        resultMap.put("decrease", decrease);
        return new ResponseEntity<>(resultMap, HttpStatus.OK);
    }

    /* 获取价格类型字段 */
    private static String getPriceType(String another, User user) {
        String price_type = "";
        Integer permission_id = user.getPermission_id();
        if (permission_id == 0 || permission_id == 3) {
            // 0 零售 price
            price_type = another + ".price";
        } else if (permission_id == 1) {
            // 1 内销 dealer_price
            price_type = another + ".dealer_price as price";
        } else if (permission_id == 2) {
            // 2 外销 overseas_price
            price_type = another + ".overseas_price as price";
        }
        return price_type;
    }

}
